package org.hospital.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.hospital.entity.Clinic;
import org.hospital.entity.Department;
import org.hospital.entity.Employee;
import org.hospital.entity.Log;
import org.hospital.entity.Position;
import org.hospital.service.ClinicService;
import org.hospital.service.DepartmentService;
import org.hospital.service.LogService;
import org.hospital.service.LoginService;
import org.hospital.service.PermissionService;
import org.hospital.util.Constant;
import org.hospital.util.DateUtil;
import org.hospital.util.Md5Util;
import org.hospital.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by pismery on 2017-10-26.
 */
@Controller
@RequestMapping("loginController")
public class LoginController {

	@Autowired
	private LoginService loginService;
	@Autowired
	private PermissionService pmService;
	@Autowired
	private LogService lService;
	@Autowired
	private ClinicService cService;
	@Autowired
	private DepartmentService dpmService;

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/json;charset=utf-8")
	public String login(WebRequest request, HttpSession session, HttpServletRequest req) {
		
		String account = request.getParameter("account");
		String pwd = Md5Util.getMd5(request.getParameter("pwd"));
		String ip = getIp(req);
		
		//判断用户账号密码、登录ip地址合法性
		Employee e = loginService.login(account, pwd, ip);
		if (e == null) {
			return StringUtil.setResult(401, "账号密码错误或登录ip地址不合法", "");
		}
		
		//设置登录用户session
		session.setAttribute("employee", e);
		//获取用户权限
		JSONObject permissionJO = pmService.getPermissionJO(e); 
		
		//格式化输出结果
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Position position = pmService.getPositionByid(e.getPositionId());
		Clinic clinic = cService.getByid(e.getClinicId());
		Department dpm = dpmService.getByid(e.getDepartmentId());
		JSONObject resultJO = new JSONObject();
		resultJO.put("employeeId", e.getEmployeeId());
		resultJO.put("employeeName", e.getName());
		resultJO.put("employeeCode", e.getEmployeeCode());
		resultJO.put("employeeAge", e.getAge());
		resultJO.put("employeeSex", e.getSex());
		resultJO.put("loginTime", sdf.format(e.getLoginTime()));
		resultJO.put("positionId", e.getPositionId());
		resultJO.put("positionName", position.getName());
		resultJO.put("positionRank", position.getRank());
		resultJO.put("clinicId", clinic.getClinicId());
		resultJO.put("clinicName", clinic.getName());
		resultJO.put("departmentId", dpm.getDepartmentId());
		resultJO.put("departmentName", dpm.getName());
		resultJO.put("permission", permissionJO);
		
		Log log = new Log();
		log.setEmployeeId(e.getEmployeeId());
		log.setOperate(Constant.LOGIN.getName());
		log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
		log.setContent("");
		lService.addEntity(log);
		
		return StringUtil.setResult(200, "登录成功",resultJO);
	}

	@ResponseBody
	@RequestMapping(value = "/logout", method = RequestMethod.POST, produces = "text/json;charset=utf-8")
	public String logout(WebRequest request, HttpSession session) {
		Employee operator = (Employee)session.getAttribute("employee");
		if(operator != null) {
			loginService.logout(operator.getEmployeeId());
		}
		session.invalidate();
		return StringUtil.setResult(200, "登出成功", "/Hospital/login.html");
	}
	
	/**
	 * 获取用户ip地址
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
